<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form :model="userForm" :rules="rulesForm" ref="userForm" label-width="100px">
        <el-form-item label="用户名称">
            <el-input disabled v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="userForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button @click="updateInfoHandler" type="primary">提交修改</el-button>
            <el-button @click="$refs.userForm.resetFields()">重置</el-button>
        </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 导入
import { mapState } from 'vuex'

export default {
  name: 'UserInfo',
  data () {
    return {
      userForm: {},
      rulesForm: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是 1~10 位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }
        ]
      }
    }
  },
  created () {
    // 浅拷贝后, this.userForm 和 this.userInfo 就是两个对象了, 做到了数据的隔离
    // 修改 userForm 的数据不会影响到 userInfo 的数据, 就不会修改 Vuex 的数据了
    // 浅拷贝给 userForm
    this.userForm = { ...this.userInfo }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    updateInfoHandler () {
      this.$refs.userForm.validate(async valid => {
        if (!valid) return
        // 发起 ajax
        const { data: res } = await this.$http.put('/my/userinfo', this.userForm)
        // console.log(res)

        // 修改失败提示
        if (res.code !== 0) return this.$message.error(res.message)

        // 修改成功提示
        this.$message.success(res.message)

        // 调用 Vuex 中的 actions 的 getUserInfo 方法，渲染更新后用户信息
        this.$store.dispatch('user/getUserInfo')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
